<template>
  <div>
    <div class="factory-query">
      <el-form class="alone-business" :model="queryFactory" ref="queryFactoryRef" :inline="true" label-width="68px">
        <el-form-item label="工厂名称" prop="factoryName">
          <el-input v-model="queryFactory.factoryName" placeholder="请输入" style="width: 240px" autosize clearable />
        </el-form-item>
        <el-form-item label="营销返点" prop="isSalesRebate">
          <el-select v-model="queryFactory.isSalesRebate" placeholder="请输入" clearable style="width: 240px">
            <el-option label="返佣" :value="1" />
            <el-option label="不返佣" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchData" style="margin-left: 10px">查询</el-button>
          <el-button plain icon="Refresh" @click="reset" style="margin-left: 10px">重置</el-button>
        </el-form-item>
      </el-form>
      <el-radio-group v-model="queryFactory.status" @change="factoryTypeChange">
        <el-radio value="" size="large">全部（{{ factoryCount.allCount }}）</el-radio>
        <el-radio :value="0" size="large">未设置（{{ factoryCount.unsetCount }}）</el-radio>
        <el-radio :value="1" size="large">待审批（{{ factoryCount.approvalPending }}）</el-radio>
        <el-radio :value="6" size="large">即将到期（{{ factoryCount.unexpiredCount }}）</el-radio>
        <el-radio :value="2" size="large">待开始（{{ factoryCount.unOpenCount }}）</el-radio>
        <el-radio :value="3" size="large">已开启（{{ factoryCount.enabledCount }}）</el-radio>
        <el-radio :value="4" size="large">续约中（{{ factoryCount.renewingCount }}）</el-radio>
      </el-radio-group>
      <!-- <div>
        <el-input
          v-model="queryFactory.factoryName"
          placeholder="请输入工厂名称"
          suffix-icon="Search"
          clearable
          style="width: 240px"
        />
        <el-button type="primary" icon="Search" @click="searchData" style="margin-left: 10px">查询</el-button>
        <el-button plain icon="Refresh" @click="reset" style="margin-left: 10px">重置</el-button>
      </div> -->
    </div>
    <el-table v-loading="loading" :data="factoryTable" highlight-current-row style="width: 100%; margin-top: 20px">
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column property="factoryName" label="工厂名称" width="250" />
      <el-table-column label="采集返佣" width="120">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.status === 0">未设置</el-tag>
          <el-tag type="primary" v-else-if="scope.row.status === 3">已开启</el-tag>
          <el-tag type="warning" v-else>{{
            scope.row.status === 2 ? "待开启" : scope.row.status === 1 ? "待审批" : "续约中"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="salesRebatesRatio" label="营销返佣">
        <template #default="scope">
          {{ scope.row.salesRebatesRatio ? scope.row.salesRebatesRatio + "%" : "-" }}
        </template>
      </el-table-column>
      <el-table-column property="startTime" label="返佣开始日期" />
      <el-table-column property="endTime" label="返佣截止日期" />
      <el-table-column property="residualDay" label="剩余时间（天）" width="120" />
      <el-table-column property="settingBy" label="设置人" width="120" />
      <el-table-column property="settingTime" label="设置日期" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="openFactory(scope.row)">
            {{ scope.row.status === 0 ? "设置工厂返佣" : "管理工厂返佣" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="listTotal" v-model:page="queryFactory.current" v-model:limit="queryFactory.size" @pagination="getTable" />
    <!-- 工厂抽屉 -->
    <el-drawer
      title="工厂返佣"
      v-model="drawerVisible"
      @close="closeDeawer(factoryFormRef)"
      size="550px"
      class="rebate-rules-drawer"
      append-to-body
    >
      <!-- factoryForm.approvalStatus审批状态;0:无审批，1：设置工厂返佣审批，2：取消工厂返佣审批，3：调整返佣审批,4:调整营销返点审批 -->
      <el-alert v-if="factoryForm.approvalStatus == 4" class="alert-primary" :closable="false" show-icon>
        <template #title>
          <div class="alert-primary-title">
            <div>营销返佣比例已调整为{{ factoryForm.newSalesRebatesRatio }}%，待内部审批通过后生效</div>
            <el-button type="primary" link @click="openRevocationApplyDialog"> 撤销修改 </el-button>
          </div>
        </template>
      </el-alert>
      <el-alert v-if="factoryForm.approvalStatus == 2" type="warning" :closable="false" show-icon>
        <template #title>
          <div>
            <el-tag type="warning">待审核</el-tag>
            已发起返佣取消申请，待内部审核通过后生效
          </div>
        </template>
      </el-alert>
      <el-alert v-if="factoryForm.approvalStatus === 1" type="warning" :closable="false" show-icon>
        <template #title>
          <div>
            <el-tag type="warning">待审核</el-tag>
            返佣规则设置成功，待内部审核通过后生效
          </div>
        </template>
      </el-alert>
      <!-- renewRatioDetailVos续约返佣比例 -->
      <el-alert v-if="factoryForm.renewRatioDetailVos" class="alert-primary" :closable="false" show-icon>
        <template #title>
          <div class="alert-primary-title">
            <div>已调整续约后的返点比例{{ factoryForm.approvalStatus == 3 ? "，待内部审批后生效" : "" }}</div>
            <el-button type="primary" link @click="openRenewalDialog"> 撤销调整 </el-button>
          </div>
        </template>
      </el-alert>
      <div class="spase" v-loading="drawerLoading">
        <el-scrollbar>
          <el-form
            style="width: 100%"
            ref="factoryFormRef"
            label-position="top"
            :model="factoryForm"
            :rules="factoryRules"
            label-width="80px"
          >
            <el-form-item label="工厂名称">
              <div>{{ factoryForm.factoryName }}</div>
            </el-form-item>
            <el-form-item label="返佣开始时间" prop="startTime">
              <el-date-picker
                v-model="factoryForm.startTime"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :clearable="false"
                placeholder="请选择返佣开始时间"
                :disabled="!isEdit || (factoryForm.status !== 0 && factoryForm.status !== 1 && factoryForm.status !== 2)"
              />
              <el-select
                v-model="factoryForm.cycle"
                v-if="isEdit"
                placeholder="返佣周期"
                :disabled="!isEdit || (factoryForm.status !== 0 && factoryForm.status !== 1 && factoryForm.status !== 2)"
                style="width: 80px; margin-left: 10px"
              >
                <el-option label="年" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="返佣周期" v-if="!isEdit">
              <el-select v-model="factoryForm.cycle" :disabled="!isEdit" placeholder="返佣周期" style="width: 80px">
                <el-option label="年" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="到期是否续约" prop="renew">
              <el-radio-group
                v-model="factoryForm.renew"
                v-if="isEdit"
                :disabled="
                  factoryForm.status !== 0 && factoryForm.status !== 1 && factoryForm.status !== 2 && factoryForm.status !== 3
                "
              >
                <el-radio :value="1">自动续约</el-radio>
                <el-radio :value="0">不自动续约</el-radio>
              </el-radio-group>
              <div class="manage-renewal" v-else>
                <div>{{ factoryForm.renew === 1 ? "自动续约" : "不自动续约" }}</div>
                <el-button
                  v-if="factoryForm.renew == 1 && factoryForm.status !== 1 && factoryForm.status !== 4"
                  type="primary"
                  link
                  @click="openRenewalDrawer"
                >
                  调整续约返点
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="营销返点" prop="cpaFactorySalesRebateSetDto.salesRebatesRatio">
              <el-input-number
                class="hidden-controls"
                v-model="factoryForm.cpaFactorySalesRebateSetDto.salesRebatesRatio"
                :precision="2"
                :step="0.1"
                :min="1"
                :max="99.99"
                :disabled="!isEdit"
              />%
            </el-form-item>
            <el-form-item label="营销返佣分配" prop="" required>
              <el-table :data="factoryForm.renew1Table" highlight-current-row style="width: 100%">
                <el-table-column property="name" label="分配对象"></el-table-column>
                <el-table-column property="commissionRatio" label="返点（%）">
                  <template #default="scope">
                    <el-input-number
                      class="hidden-controls"
                      v-model="scope.row.commissionRatio"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      :max="100"
                      :disabled="!isEdit"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <!-- 无续约返点设置显示table -->
            <el-form-item label="集采返点" v-if="!factoryForm.renewRatioDetailVos">
              <div style="width: 100%; border: 1px solid #e9e9eb">
                <el-table :data="factoryForm.cpaFactoryRatioSetDTOs" highlight-current-row style="width: 100%">
                  <el-table-column label="序号" type="index" width="50"></el-table-column>
                  <el-table-column property="amount" label="销售金额（W）">
                    <template #default="scope">
                      <el-input-number
                        class="hidden-controls"
                        v-model="scope.row.amount"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        :disabled="!isEdit || (factoryForm.status !== 0 && factoryForm.status !== 1)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column property="commissionRatio" label="厂家返点（%）">
                    <template #default="scope">
                      <el-input-number
                        class="hidden-controls"
                        v-model="scope.row.commissionRatio"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        :max="100"
                        :disabled="!isEdit || (factoryForm.status !== 0 && factoryForm.status !== 1)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="isEdit && (factoryForm.status === 0 || factoryForm.status === 1)"
                    fixed="right"
                    label="操作"
                    width="80"
                  >
                    <template #default="scope">
                      <el-button
                        v-if="factoryForm.cpaFactoryRatioSetDTOs.length > 1"
                        link
                        type="primary"
                        @click="delFactory(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button
                  v-if="isEdit && (factoryForm.status === 0 || factoryForm.status === 1)"
                  text
                  type="primary"
                  icon="CirclePlusFilled"
                  @click="addItem"
                >
                  继续添加
                </el-button>
              </div>
            </el-form-item>
            <!-- 有续约返点设置后显示table -->
            <el-form-item label="集采返点" v-else>
              <el-row style="width: 100%; border: 1px solid #e9e9eb">
                <el-table :data="factoryForm.cpaFactoryRatioSetDTOs" highlight-current-row style="width: 50%">
                  <el-table-column label="续约前">
                    <el-table-column label="销售金额（W）" prop="amount"> </el-table-column>
                    <el-table-column label="厂家返点（%）" prop="commissionRatio"></el-table-column>
                  </el-table-column>
                </el-table>
                <el-table :data="factoryForm.renewRatioDetailVos" highlight-current-row style="width: 50%">
                  <el-table-column label="续约后">
                    <el-table-column label="销售金额（W）" prop="amount"> </el-table-column>
                    <el-table-column label="厂家返点（%）" prop="commissionRatio"></el-table-column>
                  </el-table-column>
                </el-table>
              </el-row>
            </el-form-item>
            <el-form-item label="备注说明">
              <el-input
                v-model="factoryForm.remark"
                type="textarea"
                placeholder="请输入"
                :autosize="{ minRows: 2, maxRows: 4 }"
                :maxlength="200"
                style="width: 100%"
                autosize
                clearable
                :disabled="
                  !isEdit ||
                  (factoryForm.status !== 0 &&
                    factoryForm.status !== 1 &&
                    factoryForm.status !== 2 &&
                    factoryForm.status !== 3 &&
                    factoryForm.status !== 4)
                "
              />
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <template #footer>
        <div style="text-align: center">
          <template v-if="factoryForm.approvalStatus == 2">
            <el-button class="btn" @click="openRevocationApplyDialog">撤回取消申请</el-button>
          </template>
          <template v-else>
            <template v-if="isEdit">
              <el-button class="btn" @click="closeDeawer(factoryFormRef)">取 消</el-button>
              <el-button class="btn" :loading="buttonLoading" type="primary" @click="handelSubmit(factoryFormRef)"
                >确 定</el-button
              >
            </template>
            <template v-if="!isEdit">
              <!-- 续约中，不允许发起取消 -->
              <el-button
                v-if="factoryForm.approvalStatus !== 2 && factoryForm.approvalStatus !== 3 && factoryForm.status !== 4"
                class="btn"
                @click="openDialog"
                >取消返佣</el-button
              >
              <el-button class="btn" :loading="buttonLoading" type="primary" @click="handelEdit">编辑</el-button>
            </template>
          </template>
        </div>
      </template>
    </el-drawer>
    <!-- 调整续约返点抽屉 -->
    <el-drawer
      title="调整续约返点"
      v-model="renewalDrawer"
      @close="closeRenewalDrawer(renewalFormRef)"
      size="500px"
      append-to-body
      class="rebate-rules-drawer"
    >
      <el-alert class="alert-primary" :closable="false" show-icon>
        <template #title>
          <div>续约时，系统默认沿用当时周期的返点，您也可以提前修改。</div>
        </template>
      </el-alert>
      <div class="spase">
        <el-scrollbar max-height="calc(100vh - 90px)">
          <el-form
            style="width: 100%"
            ref="renewalFormRef"
            :model="renewalForm"
            :rules="renewalRules"
            label-position="top"
            label-width="80px"
          >
            <el-form-item label="工厂名称">
              <div>{{ renewalForm.factoryName }}</div>
            </el-form-item>

            <el-form-item label="集采返点">
              <div style="width: 100%; border: 1px solid #e9e9eb">
                <el-table :data="renewalForm.cpaFactoryRatioSetDTOs" highlight-current-row style="width: 100%">
                  <el-table-column label="序号" type="index" width="50" />
                  <el-table-column property="amount" label="销售金额（W）">
                    <template #default="scope">
                      <el-input-number class="hidden-controls" v-model="scope.row.amount" :precision="2" :step="0.1" :min="0" />
                    </template>
                  </el-table-column>
                  <el-table-column property="commissionRatio" label="厂家返点（%）">
                    <template #default="scope">
                      <el-input-number
                        class="hidden-controls"
                        v-model="scope.row.commissionRatio"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        :max="100"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="80">
                    <template #default="scope">
                      <el-button
                        v-if="renewalForm.cpaFactoryRatioSetDTOs.length > 1"
                        link
                        type="primary"
                        @click="delRenewal(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button text type="primary" icon="CirclePlusFilled" @click="addRenewalItem"> 继续添加 </el-button>
              </div>
            </el-form-item>
            <el-form-item label="调整原因" prop="changeReason">
              <el-input
                v-model="renewalForm.changeReason"
                type="textarea"
                placeholder="请输入"
                :autosize="{ minRows: 2, maxRows: 4 }"
                :maxlength="200"
                style="width: 100%"
                autosize
                clearable
              />
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeRenewalDrawer(renewalFormRef)">取 消</el-button>
          <el-button class="btn" :loading="submitRenewalBtn" type="primary" @click="handelSubmitRenewal(renewalFormRef)"
            >确 定</el-button
          >
        </div>
      </template>
    </el-drawer>
    <!-- 待开启/待审核 撤回弹窗 -->
    <el-dialog
      v-model="unauditedDialog"
      width="474"
      title="取消返佣"
      :close-on-click-modal="false"
      @close="closeRenewal(dialogFormRef)"
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules" label-position="top">
        <el-form-item label="备注说明" prop="cancelReason">
          <el-input
            v-model="dialogForm.cancelReason"
            type="textarea"
            placeholder="请输入"
            :autosize="{ minRows: 2, maxRows: 4 }"
            :maxlength="200"
            style="width: 100%"
            autosize
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeRenewal(dialogFormRef)">取消</el-button>
          <el-button class="btn" :loading="dialogRenewaBtn" type="primary" @click="toRenewal(dialogFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 已开启  撤回弹窗-->
    <!-- <el-dialog v-model="initiate" width="474" title="取消返佣" :close-on-click-modal="false" @close="closeRenewal(dialogFormRef)">
      <div style="text-align: center">
        <el-icon color="#F56C6C" size="70"><Warning /></el-icon>
      </div>
      <div style="text-align: center; margin-top: 40px; margin-bottom: 30px">
        当前供应商已开启返佣，需内部审核后才可以取消，请确认是否发起取消申请？
      </div>
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules" label-position="top">
        <el-form-item prop="cancelReason">
          <el-input
            v-model="dialogForm.cancelReason"
            type="textarea"
            placeholder="请输入"
            :autosize="{ minRows: 2, maxRows: 4 }"
            style="width: 100%"
            autosize
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeRenewal(dialogFormRef)">取消</el-button>
          <el-button class="btn" :loading="dialogRenewaBtn" type="primary" @click="toRenewal(dialogFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog> -->
    <!-- 调整续约返点  撤回弹窗-->
    <el-dialog v-model="renewalDialog" width="474" @close="closeRenewalDialog">
      <div style="text-align: center">
        <el-icon color="#F56C6C" size="70"><Warning /></el-icon>
      </div>
      <div style="text-align: center; margin-top: 40px; margin-bottom: 30px">是否撤销续约返点设置？</div>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeRenewalDialog">取消</el-button>
          <el-button class="btn" :loading="revocationRenewalBtn" type="primary" @click="revocationRenewalSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 撤回 取消返佣申请 弹窗-->
    <el-dialog v-model="revocationApplyDialog" width="474" @close="closeRevocationApplyDialog">
      <div style="text-align: center">
        <el-icon color="#F56C6C" size="70"><Warning /></el-icon>
      </div>
      <div style="text-align: center; margin-top: 40px; margin-bottom: 30px">{{ dialogTitle }}</div>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeRevocationApplyDialog">取消</el-button>
          <el-button class="btn" :loading="revocationApplyBtn" type="primary" @click="revocationApplySubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import {
  factoryList,
  setFactoryRatio,
  getFactoryRatioDetail,
  updateFactoryRatio,
  deleteFactoryRatio,
  changeRenewRatio,
  recallApproval,
  deleteRenew,
  factoryCommissionRuleCount
} from "@/api/system/rebateRules/index";
import { max } from "lodash";

// 工厂搜索条件
const queryFactory = ref({
  status: "",
  factoryName: "",
  isSalesRebate: null,
  current: 1,
  size: 10
});
const factoryTypeChange = value => {
  getTable();
};
const searchData = () => {
  getTable();
};
// 工厂表格
const factoryTable = ref([]);
// 工厂表格总数
const listTotal = ref(0);
// 工厂抽屉
const drawerVisible = ref(false);
// 工厂表单
const factoryForm = ref({
  name: "",
  time: "",
  cycle: 1,
  renew: "",
  cpaFactoryRatioSetDTOs: [
    {
      amount: null,
      commissionRatio: null
    }
  ],
  cpaFactorySalesRebateSetDto: {
    salesRebatesRatio: 0,
    introducerRatio: 0,
    channelRatio: 0,
    exhibitionHallRatio: 0,
    platformRatio: 0
  },
  remark: ""
});
const loading = ref(false);
const factoryFormRef = ref();
// 工厂表单校验
const factoryRules = ref({
  startTime: [{ type: "date", required: true, message: "返佣开始时间不能为空", trigger: "change" }],
  renew: [{ required: true, message: "到期是否续约必须选", trigger: "change" }],
  "cpaFactorySalesRebateSetDto.salesRebatesRatio": [{ required: true, message: "请输入工厂营销返点，需>=1%", trigger: "blur" }]
});

// 提交按钮loading
const buttonLoading = ref(false);

// 取消返佣弹窗
const unauditedDialog = ref(false);
// const initiate = ref(false);

// 是否编辑
const isEdit = ref(true);

// 重置
const reset = () => {
  queryFactory.value = {
    factoryName: "",
    isSalesRebate: null,
    status: queryFactory.value.status,
    current: 1,
    size: 10
  };
  getTable();
};
// 打开工厂抽屉
const openFactory = row => {
  drawerLoading.value = false;
  drawerVisible.value = true;
  if (row.status === 0) {
    isEdit.value = true;
    factoryForm.value = Object.assign({}, row, {
      startTime: "",
      cycle: 1,
      renew: "",
      renew1Table: [
        {
          name: "工厂开拓人员",
          commissionRatio: null
        },
        {
          name: "渠道",
          commissionRatio: null
        },
        {
          name: "展厅",
          commissionRatio: null
        },
        {
          name: "家装通",
          commissionRatio: null
        }
      ],
      cpaFactoryRatioSetDTOs: [
        {
          amount: null,
          commissionRatio: null
        }
      ],
      cpaFactorySalesRebateSetDto: {
        salesRebatesRatio: null,
        introducerRatio: null,
        channelRatio: null,
        exhibitionHallRatio: null,
        platformRatio: null
      },
      status: 0,
      remark: ""
    });
  } else {
    isEdit.value = false;
    getRatioDetail(row);
  }
};

const drawerLoading = ref(false);
// 获取工厂返佣详情
const getRatioDetail = row => {
  drawerLoading.value = true;
  getFactoryRatioDetail(row.factoryCommissionId).then(res => {
    res.data.cpaFactoryRatioDetailVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.commissionRatio);
    });
    res.data.renewRatioDetailVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.commissionRatio);
    });

    res.data.renew1Table = [
      {
        name: "工厂开拓人员",
        commissionRatio: Number(res.data.cpaFactorySalesRebateDetailVo?.introducerRatio)
      },
      {
        name: "渠道",
        commissionRatio: Number(res.data.cpaFactorySalesRebateDetailVo?.channelRatio)
      },
      {
        name: "展厅",
        commissionRatio: Number(res.data.cpaFactorySalesRebateDetailVo?.exhibitionHallRatio)
      },
      {
        name: "家装通",
        commissionRatio: Number(res.data.cpaFactorySalesRebateDetailVo?.platformRatio)
      }
    ];
    res.data.cpaFactorySalesRebateSetDto = {
      salesRebatesRatio: Number(res.data.cpaFactorySalesRebateDetailVo?.salesRebatesRatio) || null
    };

    factoryForm.value = res.data;
    factoryForm.value.cpaFactoryRatioSetDTOs = res.data.cpaFactoryRatioDetailVos;
    console.log(factoryForm.value);
    drawerLoading.value = false;
  });
};

// 关闭抽屉
const closeDeawer = formRef => {
  if (!formRef) return;
  drawerVisible.value = false;
  buttonLoading.value = false;
  formRef.resetFields();
};
// 删除工厂表单表格
const delFactory = index => {
  factoryForm.value.cpaFactoryRatioSetDTOs.splice(index, 1);
};
// 添加工厂表单数据
const addItem = () => {
  factoryForm.value.cpaFactoryRatioSetDTOs.push({ amount: 0, commissionRatio: 0 });
};
// 提交工厂表单
const handelSubmit = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      let renew1Table = factoryForm.value.renew1Table;
      let numJudge = renew1Table.every(item => item.commissionRatio >= 0);
      if (!numJudge) {
        ElMessage.error("请输入营销返佣分配规则返点");
        return;
      }

      let sum = 0;
      renew1Table.map(item => {
        sum = sum + item.commissionRatio * 1000;
      });
      if (sum / 1000 != factoryForm.value.cpaFactorySalesRebateSetDto.salesRebatesRatio) {
        ElMessage.error("返点总和必须等于营销返佣比例");
        return;
      }

      let cpaFactoryRatioSetDTOs = factoryForm.value.cpaFactoryRatioSetDTOs;
      let amountJudge = cpaFactoryRatioSetDTOs.every(item => item.amount > 0);
      if (!amountJudge) {
        ElMessage.error("请输入销售金额");
        return;
      }
      // 销售金额多条数据，判断下一阶梯销售金额必须>上一级,
      if (cpaFactoryRatioSetDTOs.length > 1) {
        for (let i = 0; i < cpaFactoryRatioSetDTOs.length; i++) {
          let amount = cpaFactoryRatioSetDTOs[i].amount;
          if (i > 0) {
            if (amount <= cpaFactoryRatioSetDTOs[i - 1].amount) {
              ElMessage.error("销售金额输入错误");
              return;
            }
          }
        }
      }
      // 返点比例多条数据，判断下一阶梯比例必须>=上一级,
      if (cpaFactoryRatioSetDTOs.length > 1) {
        for (let i = 0; i < cpaFactoryRatioSetDTOs.length; i++) {
          let commissionRatio = cpaFactoryRatioSetDTOs[i].commissionRatio;
          if (i > 0) {
            if (commissionRatio < cpaFactoryRatioSetDTOs[i - 1].commissionRatio) {
              ElMessage.error("厂家返点输入错误");
              return;
            }
          }
        }
      }

      let cpaFactory = {
        cpaFactorySalesRebateSetDto: {
          salesRebatesRatio: factoryForm.value.cpaFactorySalesRebateSetDto.salesRebatesRatio,
          introducerRatio: renew1Table.find(item => {
            return item.name == "工厂开拓人员";
          }).commissionRatio,
          channelRatio: renew1Table.find(item => {
            return item.name == "渠道";
          }).commissionRatio,
          exhibitionHallRatio: renew1Table.find(item => {
            return item.name == "展厅";
          }).commissionRatio,
          platformRatio: renew1Table.find(item => {
            return item.name == "家装通";
          }).commissionRatio
        }
      };
      let postData = { ...factoryForm.value, ...cpaFactory };

      buttonLoading.value = true;
      if (factoryForm.value.status === 0) {
        setFactoryRatio(postData)
          .then(res => {
            closeDeawer(factoryFormRef.value);
            ElMessage.success("设置成功");
            getTable();
          })
          .catch(err => {
            buttonLoading.value = false;
          });
      } else {
        updateFactoryRatio(postData)
          .then(res => {
            closeDeawer(factoryFormRef.value);
            ElMessage.success("编辑成功");
            getTable();
          })
          .catch(err => {
            buttonLoading.value = false;
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 编辑修改表单
const handelEdit = () => {
  if (factoryForm.value.approvalStatus !== 0) {
    ElMessage.error("有待审批正在进行，不能进行编辑");
    return;
  }
  isEdit.value = true;
};

// 续约返点抽屉
const renewalDrawer = ref(false);
// 续约表格
const renewalForm = ref({
  cpaFactoryRatioSetDTOs: [
    {
      amount: null,
      commissionRatio: null
    }
  ],
  changeReason: ""
});
const renewalRules = ref({
  changeReason: [{ required: true, message: "请输入调整原因", trigger: "change" }]
});
const renewalFormRef = ref();
const submitRenewalBtn = ref(false);
// 打开续约返点抽屉
const openRenewalDrawer = () => {
  if (factoryForm.value.renewRatioDetailVos && factoryForm.value.renewRatioDetailVos.length > 0) {
    ElMessage.error("已调整续约返点，如需再次调整，请先撤销原调整记录");
    return;
  }

  if (factoryForm.value.approvalStatus !== 0) {
    ElMessage.error("有待审批正在进行，不能进行调整");
    return;
  }

  renewalDrawer.value = true;
  renewalForm.value.factoryCommissionId = factoryForm.value.factoryCommissionId;
  renewalForm.value.factoryName = factoryForm.value.factoryName;
  renewalForm.value.cpaFactoryRatioSetDTOs = factoryForm.value?.renewRatioDetailVos || [
    {
      amount: null,
      commissionRatio: null
    }
  ];
};
// 关闭续约返点抽屉
const closeRenewalDrawer = formRef => {
  if (!formRef) return;
  renewalDrawer.value = false;
  submitRenewalBtn.value = false;
  formRef.resetFields();
};
// 删除续约返点表单表格
const delRenewal = index => {
  renewalForm.value.cpaFactoryRatioSetDTOs.splice(index, 1);
};
// 添加续约返点表单数据
const addRenewalItem = () => {
  renewalForm.value.cpaFactoryRatioSetDTOs.push({ amount: 0, commissionRatio: 0 });
};
// 提交续约表单
const handelSubmitRenewal = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      let cpaFactoryRatioSetDTOs = renewalForm.value.cpaFactoryRatioSetDTOs;
      let amountJudge = cpaFactoryRatioSetDTOs.every(item => item.amount > 0);
      if (!amountJudge) {
        ElMessage.error("请输入销售金额");
        return;
      }
      // 销售金额多条数据，判断下一阶梯销售金额必须>上一级,
      if (cpaFactoryRatioSetDTOs.length > 1) {
        for (let i = 0; i < cpaFactoryRatioSetDTOs.length; i++) {
          let amount = cpaFactoryRatioSetDTOs[i].amount;
          if (i > 0) {
            if (amount <= cpaFactoryRatioSetDTOs[i - 1].amount) {
              ElMessage.error("销售金额输入错误");
              return;
            }
          }
        }
      }
      // 返点比例多条数据，判断下一阶梯比例必须>=上一级,
      if (cpaFactoryRatioSetDTOs.length > 1) {
        for (let i = 0; i < cpaFactoryRatioSetDTOs.length; i++) {
          let commissionRatio = cpaFactoryRatioSetDTOs[i].commissionRatio;
          if (i > 0) {
            if (commissionRatio < cpaFactoryRatioSetDTOs[i - 1].commissionRatio) {
              ElMessage.error("厂家返点输入错误");
              return;
            }
          }
        }
      }
      console.log(renewalForm.value);
      submitRenewalBtn.value = true;
      changeRenewRatio(renewalForm.value)
        .then(res => {
          closeRenewalDrawer(renewalFormRef.value);
          getRatioDetail(renewalForm.value);
          ElMessage.success(res.msg);
          getTable();
        })
        .catch(err => {
          submitRenewalBtn.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 取消返佣表单
const dialogForm = ref({ cancelReason: [] });
const dialogFormRules = ref({
  cancelReason: [{ required: true, message: "请输入取消原因", trigger: "blur" }]
});
const dialogFormRef = ref();
const dialogRenewaBtn = ref(false);
// 打开取消返佣弹窗
const openDialog = () => {
  unauditedDialog.value = true;
  // if (factoryForm.value.status === 1 || factoryForm.value.status === 2) {
  //   unauditedDialog.value = true;
  // } else if (factoryForm.value.status === 3) {
  //   initiate.value = true;
  // }
};
// 关闭取消返佣弹窗
const closeRenewal = formRef => {
  if (!formRef) return;
  unauditedDialog.value = false;
  // initiate.value = false;
  dialogRenewaBtn.value = false;
  formRef.resetFields();
};

// 确定撤回返佣
const toRenewal = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      let params = {
        factoryCommissionId: factoryForm.value.factoryCommissionId,
        cancelReason: dialogForm.value.cancelReason
      };
      console.log(params);
      dialogRenewaBtn.value = true;
      deleteFactoryRatio(params)
        .then(res => {
          closeRenewal(dialogFormRef.value);
          closeDeawer(factoryFormRef.value);
          ElMessage.success(res.msg);
          getTable();
        })
        .catch(err => {
          dialogRenewaBtn.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 撤销续约弹窗
const renewalDialog = ref(false);
const revocationRenewalBtn = ref(false);
const openRenewalDialog = () => {
  renewalDialog.value = true;
};
// 关闭取消返佣弹窗
const closeRenewalDialog = () => {
  renewalDialog.value = false;
  revocationRenewalBtn.value = false;
};
const revocationRenewalSubmit = () => {
  revocationRenewalBtn.value = true;
  if (factoryForm.value.approvalStatus == 3) {
    allRecallApproval(3);
  } else {
    deleteRenewSet();
  }
};

// 取消 续约设置
const deleteRenewSet = () => {
  deleteRenew({ factoryCommissionId: factoryForm.value.factoryCommissionId })
    .then(res => {
      closeRenewalDialog();
      getRatioDetail(factoryForm.value);
      ElMessage.success("取消成功");
    })
    .catch(err => {
      revocationRenewalBtn.value = false;
    });
};

// 撤回取消返佣申请/撤销营销点调整申请
const revocationApplyDialog = ref(false);
const revocationApplyBtn = ref(false);
const dialogTitle = ref("");
const openRevocationApplyDialog = () => {
  if (factoryForm.value.approvalStatus == 4) {
    dialogTitle.value = "请确认是否撤回营销返点比例调整申请";
  } else {
    dialogTitle.value = "请确认是否撤回取消申请";
  }
  revocationApplyDialog.value = true;
};
const closeRevocationApplyDialog = () => {
  revocationApplyDialog.value = false;
  revocationApplyBtn.value = false;
};
const revocationApplySubmit = () => {
  revocationApplyBtn.value = true;
  allRecallApproval(factoryForm.value.approvalStatus);
};

// 撤销 取消返佣/续约调整/营销点调整 申请
const allRecallApproval = approvalStatus => {
  let params = {
    factoryCommissionId: factoryForm.value.factoryCommissionId,
    approvalStatus
  };
  recallApproval(params)
    .then(res => {
      closeRevocationApplyDialog();
      closeRenewalDialog();
      getRatioDetail(factoryForm.value);
      ElMessage.success(res.msg);
    })
    .catch(err => {
      revocationApplyBtn.value = false;
      revocationRenewalBtn.value = false;
    });
};

// 获取表格数据
const getTable = () => {
  loading.value = true;
  factoryList(queryFactory.value).then(res => {
    res.data.list?.forEach(item => {
      item.endTime = item.endTime?.split(" ")[0];
      item.startTime = item.startTime?.split(" ")[0];
      item.settingTime = item.settingTime?.split(" ")[0];
    });
    factoryTable.value = res.data.list;
    listTotal.value = res.data.total;
    switch (queryFactory.value.status) {
      case "":
        factoryCount.value.allCount = res.data.total;
        break;
      case 0:
        factoryCount.value.unsetCount = res.data.total;
        break;
      case 1:
        factoryCount.value.approvalPending = res.data.total;
        break;
      case 6:
        factoryCount.value.unexpiredCount = res.data.total;
        break;
      case 2:
        factoryCount.value.unOpenCount = res.data.total;
        break;
      case 3:
        factoryCount.value.enabledCount = res.data.total;
        break;
      case 4:
        factoryCount.value.renewingCount = res.data.total;
        break;
      default:
        break;
    }
    loading.value = false;
  });
};

const factoryCount = ref({
  allCount: 0,
  unsetCount: 0,
  approvalPending: 0,
  unexpiredCount: 0,
  unOpenCount: 0,
  enabledCount: 0,
  renewingCount: 0
});

// 工厂返佣统计各状态数据量
const getFactoryCommissionRuleCount = () => {
  factoryCommissionRuleCount().then(res => {
    factoryCount.value = res.data;
  });
};

onMounted(() => {
  getFactoryCommissionRuleCount();
  getTable();
});
</script>

<style lang="scss" scoped>
.factory-query {
}

.manage-renewal {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.btn {
  width: 120px;
  height: 36px;
  line-height: 36px;
}
.table-rules {
  margin-bottom: 14px;
}
</style>
<style lang="scss">
.rebate-rules {
  &-drawer {
    .el-drawer__header {
      margin-bottom: 0;
      padding-bottom: 10px;
      border-bottom: 1px solid #dcdfe6;
    }
    .el-drawer__body {
      padding: 0;
      .alert-primary {
        background-color: #e3f0fe;
        color: #000;
        .el-alert__icon {
          color: #0052d9;
        }
        .el-alert__content {
          width: 100%;
        }
        &-title {
          display: flex;
          justify-content: space-between;
        }
      }
      .spase {
        padding: 20px;
        .hidden-controls .el-input-number__decrease,
        .hidden-controls .el-input-number__increase {
          display: none; /* 隐藏增加和减少按钮 */
        }
        .hidden-controls .el-input__wrapper {
          padding: 0 10px;
        }
      }
    }
  }
  .el-dialog {
    margin-top: 200px;
  }
}
</style>
